package main.java.Fzy.Test;

public class Test04 {
    public static void main(String[] args) {
        MyBLink myBLink = new MyBLink();

        myBLink.addTail(1);
        myBLink.addTail(2);
        myBLink.addTail(3);
        myBLink.add(2,7);
        myBLink.HeadPrint();
        System.out.println("-----------");
        myBLink.TailPrint();
        System.out.println("-----------");
        myBLink.delete(2);
        myBLink.HeadPrint();
        System.out.println("-----------");
        myBLink.TailPrint();
        System.out.println("-----------");
        myBLink.destroy();
        myBLink.HeadPrint();
        myBLink.TailPrint();
    }
}
/*
* 双向链表
*
* 创建
* 销毁
* 结点插入
* 结点删除
* 结点遍历
* */
class MyBLink{

    BLink head;
    int size;

    //创建
    MyBLink(){
        head = new BLink(0);  //创建头结点
        size = 0;
    }

    //销毁
    public void destroy(){
        head.next = null;
        System.out.println("链表已经让销毁");
    }

    public void addTail(int val){
        add(size,val);
    }

    //结点插入
    public void add(int k,int val){   //k代表插入位置

        BLink node = new BLink(val);  //创建要插入的结点
        BLink cur = head;
        for(int i = 0;i<k;i++){
            cur = cur.next;
        }
        if(cur.next != null){
            node.next = cur.next;
            cur.next.pre = node;
        }
        cur.next = node;
        node.pre = cur;
        size++;
    }

    //结点删除
    public void delete(int k){  //k代表要删除的位置
        BLink cur = head;
        for(int i = 0;i<k;i++){
            cur = cur.next;
        }
        cur.next = cur.next.next;
        cur.next.pre = cur;
    }

    //头遍历
    public void HeadPrint(){
        if(head.next == null){
            System.out.println("-----链表不存在--------");
        }
        BLink cur = head.next;
        while (cur != null){
            System.out.print(cur.val+" ");
            cur = cur.next;
        }
        System.out.println();
    }
    //尾遍历
    public void TailPrint(){
        if(head.next == null){
            System.out.println("-----链表不存在-------");
        }
        BLink cur = head;
        while (cur != null && cur.next != null){
            cur = cur.next;
        }
        while (cur != head){
            System.out.print(cur.val +" ");
            cur = cur.pre;
        }
        System.out.println();
    }
}

class BLink{
    int val;
    BLink next;  //指向后一个结点
    BLink pre;   //指向前一个结点
    BLink(){
    }
    BLink(int val){
        this.val = val;
    }
}
